package com.weetop.cfw.home_page.activity

import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.LogUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.chad.library.adapter.base.entity.MultiItemEntity
import com.weetop.cfw.R
import com.weetop.cfw.base.presenter.imp.ChooseAddressPresenterImp
import com.weetop.cfw.base.ui.activity.CommonBaseActivity
import com.weetop.cfw.base.view.ChooseAddressView
import com.weetop.cfw.bean.AllSubSiteListBean
import com.weetop.cfw.bean.HotSitesBean
import com.weetop.cfw.bean.TestBean
import com.weetop.cfw.home_page.adapter.ChooseAddressRVAdapter
import com.weetop.cfw.home_page.adapter.FilterAddressResultAdapter
import com.weetop.cfw.home_page.adapter.HotCitiesRVAdapter
import com.weetop.cfw.home_page.adapter.QuickFilterRVAdapter
import com.weetop.cfw.utils.EventBusUtils
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_choose_address.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.concurrent.TimeUnit


/**
 * 选择地址界面
 */
class ChooseAddressActivity : CommonBaseActivity(), TextWatcher, View.OnClickListener,
    ChooseAddressView {

    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.imageChooseAddressBack -> ActivityUtils.finishActivity(this)
        }
    }

    private lateinit var chooseAddressPresenterImp: ChooseAddressPresenterImp

    private lateinit var chooseAddressRVAdapter: ChooseAddressRVAdapter
    private lateinit var hotCitiesRVAdapter: HotCitiesRVAdapter
    private lateinit var quickFilterRVAdapter: QuickFilterRVAdapter
    private lateinit var filterAddressResultAdapter: FilterAddressResultAdapter
    private lateinit var searchAdapter: SearchAdapter


    private var dataBeanList: List<AllSubSiteListBean.DataBean> =
        ArrayList<AllSubSiteListBean.DataBean>()

    private var disposable: Disposable? = null

    private lateinit var chooseAddressHeaderView: View

    private lateinit var hotCityRV: RecyclerView

    private lateinit var textCurrentCityName: TextView

    private lateinit var linearLayoutManager: LinearLayoutManager

    private val res = ArrayList<MultiItemEntity>()
    private lateinit var filterLetterList: ArrayList<String>
    private lateinit var otherFilterLetterList: ArrayList<String>

    override fun getLayoutId() = R.layout.activity_choose_address

    override fun initView(savedInstanceState: Bundle?) {

        chooseAddressPresenterImp = ChooseAddressPresenterImp()
        chooseAddressPresenterImp.attachView(this)

        chooseAddressHeaderView = View.inflate(this, R.layout.layout_choose_address_rv_header, null)
        hotCityRV = chooseAddressHeaderView.findViewById(R.id.hotCityRV)
        textCurrentCityName = chooseAddressHeaderView.findViewById(R.id.textCurrentCityName)

        editSearchAddress.addTextChangedListener(this)

        setViewsOnClickListener(this, imageChooseAddressBack)
    }

    override fun initData(savedInstanceState: Bundle?) {

        val currentCityName = intent.getStringExtra(CURRENT_LOCATION_CITY_NAME)
        if (currentCityName == null) {
            textCurrentCityName.text = "暂无定位"
        } else {
            textCurrentCityName.text = currentCityName
        }

        textCurrentCityName.setOnClickListener{
       var data= AllSubSiteListBean.DataBean.SdataBean(-1)
            EventBusUtils.post(data)
        }

        chooseAddressPresenterImp.getHotSitesData(this)
        chooseAddressPresenterImp.getAllSitesListData(this)

        val hotCityList = listOf(
            TestBean("杭州市"),
            TestBean("上海市"),
            TestBean("湖州市"),
            TestBean("宁波市"),
            TestBean("绍兴市"),
            TestBean("嘉兴市"),
            TestBean("苏州市"),
            TestBean("金华市")
        )
//
//        filterAddressResultAdapter = FilterAddressResultAdapter(R.layout.layout_city_two_level,hotCityList)
//        filterResultRV.adapter = filterAddressResultAdapter

        searchAdapter = SearchAdapter(R.layout.layout_city_two_level, search)
        filterResultRV.adapter = searchAdapter

        searchAdapter.setOnItemClickListener { adapter, view, position ->
            var item =search.get(position)
            EventBusUtils.post(item)
        }

        linearLayoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        chooseAddressRVAdapter = ChooseAddressRVAdapter(res)
        chooseAddressRVAdapter.setHeaderView(chooseAddressHeaderView)
        cityInfoRV.layoutManager = linearLayoutManager
        cityInfoRV.adapter = chooseAddressRVAdapter

        filterLetterList = ArrayList()
        otherFilterLetterList = ArrayList()
        quickFilterRVAdapter =
            QuickFilterRVAdapter(R.layout.layout_quick_filter_item, filterLetterList)
        quickFilterRVAdapter.setOnItemClickListener { adapter, view, position ->
            slideSelectionPosition(position)
        }
        quickFilterRV.adapter = quickFilterRVAdapter

    }

    var search: MutableList<AllSubSiteListBean.DataBean.SdataBean> = ArrayList()

    override fun afterTextChanged(p0: Editable?) {
        if (p0 != null) {
            if (p0.isEmpty()) {
                cityInfoRV.visibility = View.VISIBLE
                quickFilterRV.visibility = View.VISIBLE
                filterResultRV.visibility = View.GONE
            } else {
                cityInfoRV.visibility = View.INVISIBLE
                quickFilterRV.visibility = View.INVISIBLE
                filterResultRV.visibility = View.VISIBLE
                search.clear()
                for (dataBean in emptyList) {
                    for (sdatum in dataBean.sdata) {
                        if (sdatum.cityname.contains(p0.toString())) {
                            search.add(sdatum)
                        }
                    }


                }
                searchAdapter.notifyDataSetChanged()
            }
        }
    }

    private class SearchAdapter(
        layoutId: Int,
        dataList: List<AllSubSiteListBean.DataBean.SdataBean>
    ) :
        BaseQuickAdapter<AllSubSiteListBean.DataBean.SdataBean, BaseViewHolder>(
            layoutId,
            dataList
        ) {

        override fun convert(helper: BaseViewHolder, item: AllSubSiteListBean.DataBean.SdataBean?) {
            helper.setText(R.id.textCityName, item?.cityname)
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onReceiveHotSitesBean(sdataBean: AllSubSiteListBean.DataBean.SdataBean) {
        finish()
    }

    override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

    }

    override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

    }

    companion object {

        const val CURRENT_LOCATION_CITY_NAME = "current_location_city_name"
    }

    override fun onDestroy() {
        super.onDestroy()
        chooseAddressPresenterImp.detachView()
    }

    /**
     * 站点数据拉取成功
     */
    override fun allSubSitesGetSuccess(allSubSiteListBean: AllSubSiteListBean?) {
        if (allSubSiteListBean != null) {
            dataBeanList = allSubSiteListBean.data
            emptyList = allSubSiteListBean.data

            val lv0Count = dataBeanList.size
            for (i in 0 until lv0Count) {//设置外层数据
                val lv0 = dataBeanList[i]
                otherFilterLetterList.add(lv0.flet)
                if (!filterLetterList.contains(lv0.flet)) {
                    filterLetterList.add(lv0.flet)
                }
                for (j in 0 until lv0.sdata.size) {
                    val p = lv0.sdata[j]
                    //设置内层数据
                    lv0.addSubItem(i, p)
                }
                res.add(lv0)
            }
            chooseAddressRVAdapter.notifyDataSetChanged()
            chooseAddressRVAdapter.expandAll()
            quickFilterRVAdapter.notifyDataSetChanged()
        }
    }

    var emptyList = emptyList<AllSubSiteListBean.DataBean>() //创建空的List

    /**
     * 热门站点数据获取成功
     */
    override fun hotSitesGetSuccess(hotSitesBean: HotSitesBean?) {
        if (hotSitesBean != null) {
            hotCitiesRVAdapter =
                HotCitiesRVAdapter(R.layout.layout_hot_cities_item, hotSitesBean.data)
            hotCityRV.adapter = hotCitiesRVAdapter
            hotCitiesRVAdapter.setOnItemClickListener { adapter, view, position ->
                EventBusUtils.post(hotSitesBean.data[position])
                finish()
            }
        }
    }

    /**
     * 滑动到指定位置
     */
    override fun slideSelectionPosition(position: Int) {
        if (disposable != null && !(disposable!!.isDisposed)) {
            disposable!!.dispose()
        }

        textLetter.visibility = View.VISIBLE

        textLetter.text = filterLetterList[position]

        val destPosition = otherFilterLetterList.indexOf(filterLetterList[position])

        var totalNumber = 0//要滑动的位置中间有多少个item
        if (destPosition > 0) {
            for (i in 0 until destPosition) {
                val itemBean = dataBeanList[i]
                totalNumber += if (itemBean.isExpanded) {//如果item是展开的，则加上其一级和二级数据的数量
                    (dataBeanList[i].sdata.size + 1)
                } else {//如果是没有展开，则加上一级item的数量
                    1
                }
            }
        }

        LogUtils.d("destPosition", totalNumber)

        linearLayoutManager.scrollToPositionWithOffset(totalNumber + 1, 0)

        disposable =
            Observable.timer(500, TimeUnit.MILLISECONDS).observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe {
                    textLetter.visibility = View.GONE
                }
    }


}
